package com.hyphenate.easeui.widget.chatrow;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMError;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMMessage.Direct;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.R;
import com.hyphenate.easeui.adapter.EaseMessageAdapter;
import com.hyphenate.easeui.dao.DaoHelper;
import com.hyphenate.easeui.dao.UserBeanDao;
import com.hyphenate.easeui.model.ChatBean;
import com.hyphenate.easeui.model.UserBean;
import com.hyphenate.easeui.utils.DateUtils;
import com.hyphenate.easeui.utils.EaseUserUtils;
import com.hyphenate.easeui.widget.EaseChatMessageList;
import com.hyphenate.easeui.widget.EaseChatMessageList.MessageListItemClickListener;

import java.util.Date;

public abstract class EaseChatRow extends LinearLayout {
    protected static final String TAG = EaseChatRow.class.getSimpleName();

    protected LayoutInflater inflater;
    protected Context context;
    protected BaseAdapter adapter;
    protected EMMessage message;
    protected int position;

    protected TextView timeStampView;
    protected ImageView userAvatarView ,vip;
    protected View bubbleLayout;
    protected TextView usernickView;

    protected TextView percentageView;
    protected ProgressBar progressBar;
    protected ImageView statusView;
    protected Activity activity;

    protected TextView ackedView;
    protected TextView deliveredView;

    protected EMCallBack messageSendCallback;
    protected EMCallBack messageReceiveCallback;

    protected MessageListItemClickListener itemClickListener;
    private Gson gson;
    private ChatBean chatBean;
    public Intent urlIntent;

    public void setUrlIntent(Intent urlIntent) {
        this.urlIntent = urlIntent;
    }

    public EaseChatRow(Context context, EMMessage message, int position, BaseAdapter adapter) {
        super(context);
        this.context = context;
        this.activity = (Activity) context;
        this.message = message;
        this.position = position;
        this.adapter = adapter;
        gson = new Gson();
        inflater = LayoutInflater.from(context);

        initView();
    }

    private void initView() {
        onInflatView();
        timeStampView = (TextView) findViewById(R.id.timestamp);
        userAvatarView = (ImageView) findViewById(R.id.iv_userhead);
        vip = (ImageView) findViewById(R.id.vip);
        bubbleLayout = findViewById(R.id.bubble);
        usernickView = (TextView) findViewById(R.id.tv_userid);

        progressBar = (ProgressBar) findViewById(R.id.progress_bar);
        statusView = (ImageView) findViewById(R.id.msg_status);
        ackedView = (TextView) findViewById(R.id.tv_ack);
        deliveredView = (TextView) findViewById(R.id.tv_delivered);

        onFindViewById();
    }

    /**
     * 根据当前message和position设置控件属性等
     *
     * @param message
     * @param position
     */
    public void setUpView(EMMessage message, int position,
                          EaseChatMessageList.MessageListItemClickListener itemClickListener) {
        this.message = message;
        this.position = position;
        this.itemClickListener = itemClickListener;

        setUpBaseView();
        onSetUpView();
        setClickListener();
    }

    private void setUpBaseView() {
        // 设置用户昵称头像，bubble背景等
        TextView timestamp = (TextView) findViewById(R.id.timestamp);
        if (timestamp != null) {
            for(Long time:( (EaseMessageAdapter)adapter).TimeList){
                if(time==message.getMsgTime()||time.equals(message.getMsgTime())){
                    timestamp.setText(DateUtils.getTimestampString(new Date(message.getMsgTime())));
                    timestamp.setVisibility(View.VISIBLE);
                    break;
                }else{
                    timestamp.setVisibility(View.GONE);
                }
            }

//            if (position == 0) {
//                timestamp.setText(DateUtils.getTimestampString(new Date(message.getMsgTime())));
//                timestamp.setVisibility(View.VISIBLE);
//            } else {
//                // 两条消息时间离得如果稍长，显示时间 设置成5分钟了
//                EMMessage prevMessage = (EMMessage) adapter.getItem(position - 1);
//                if (prevMessage != null && DateUtils.isCloseEnough(message.getMsgTime(), prevMessage.getMsgTime())) {
//                    timestamp.setVisibility(View.GONE);
//                } else {
//                    timestamp.setText(DateUtils.getTimestampString(new Date(message.getMsgTime())));
//                    timestamp.setVisibility(View.VISIBLE);
//                }
//

        }
        String str= null;
        try {
            str = message.getStringAttribute("userinfo");
            chatBean=gson.fromJson(str,ChatBean.class);

        } catch (Exception e) {
            e.printStackTrace();
        }

        if(null==chatBean)
            chatBean=new ChatBean();
        //设置头像和nick
        if(message.direct() == Direct.SEND){
            EaseUserUtils.setUserLogo(context, chatBean.getLogo(), userAvatarView);
            //发送方不显示nick
//            UserUtils.setUserNick(EMChatManager.getInstance().getCurrentUser(), usernickView);
        }else{
            EaseUserUtils.setUserLogo(context, chatBean.getLogo(), userAvatarView);
            UserBean userBean= (UserBean) DaoHelper.getInstance(context, EaseConstant.DB_NAME_CHAT).getTypeId(UserBeanDao.Properties.Imid,chatBean.getImid());
            if(null!=userBean){
                EaseUserUtils.setUserNick(userBean.getUsername(), usernickView);
            }else
                EaseUserUtils.setUserNick(chatBean.getName(), usernickView);
//            EaseUserUtils.setUserNick(message.getFrom(), usernickView);
        }


        //设置加V
//        UserBean userBean= (UserBean) DaoHelper.getInstance(context, EaseConstant.DB_NAME_CHAT).getTypeId(UserBeanDao.Properties.Imid,chatBean.getImid());
        if(null!=chatBean.getUserAuth()&& vip!=null){
            if("0".equals(chatBean.getUserAuth().getType())) {
                vip.setImageResource(R.drawable.v_huan);
                vip.setVisibility(View.VISIBLE);
            }else if("1".equals(chatBean.getUserAuth().getType())){
                vip.setImageResource(R.drawable.v_lan);
                vip.setVisibility(View.VISIBLE);
            }else{
                vip.setVisibility(View.GONE);
            }
        }else if(null!=chatBean.getUserauth()){
            if("0".equals(chatBean.getUserauth().getType())) {
                vip.setImageResource(R.drawable.v_huan);
                vip.setVisibility(View.VISIBLE);
            }else if("1".equals(chatBean.getUserauth().getType())){
                vip.setImageResource(R.drawable.v_lan);
                vip.setVisibility(View.VISIBLE);
            }else{
                vip.setVisibility(View.GONE);
            }
        } else{
            vip.setVisibility(View.GONE);
        }

        if(deliveredView != null){
            if (message.isDelivered()) {
                deliveredView.setVisibility(View.VISIBLE);
            } else {
                deliveredView.setVisibility(View.INVISIBLE);
            }
        }
        //已读状态  edg取消
//        if(ackedView != null){
//            if (message.isAcked()) {
//                if (deliveredView != null) {
//                    deliveredView.setVisibility(View.INVISIBLE);
//                }
//                ackedView.setVisibility(View.VISIBLE);
//            } else {
//                ackedView.setVisibility(View.INVISIBLE);
//            }
//        }


        if (adapter instanceof EaseMessageAdapter) {
            if (((EaseMessageAdapter) adapter).isShowAvatar())
                userAvatarView.setVisibility(View.VISIBLE);
            else
                userAvatarView.setVisibility(View.GONE);
            if (usernickView != null) {
                if (((EaseMessageAdapter) adapter).isShowUserNick())
                    usernickView.setVisibility(View.VISIBLE);
                else
                    usernickView.setVisibility(View.GONE);
            }
            if (message.direct() == Direct.SEND) {
                if (((EaseMessageAdapter) adapter).getMyBubbleBg() != null)
                    bubbleLayout.setBackgroundDrawable(((EaseMessageAdapter) adapter).getMyBubbleBg());
                // else
                // bubbleLayout.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.chatto_bg));
            } else if (message.direct() == Direct.RECEIVE) {
                if (((EaseMessageAdapter) adapter).getOtherBuddleBg() != null)
                    bubbleLayout.setBackgroundDrawable(((EaseMessageAdapter) adapter).getOtherBuddleBg());
//                else
//                    bubbleLayout.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.ease_chatfrom_bg));
            }
        }
    }

    /**
     * 设置消息发送callback
     */
    protected void setMessageSendCallback(){
        if(messageSendCallback == null){
            messageSendCallback = new EMCallBack() {

                @Override
                public void onSuccess() {

//                    Log.e("ssu-----","000000000");
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            updateView(0);

                        }
                    });
                }

                @Override
                public void onProgress(final int progress, String status) {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if(percentageView != null)
                                percentageView.setText(progress + "%");

                        }
                    });
                }

                @Override
                public void onError(int code, String error) {
                    updateView(code);
                }
            };
        }
        message.setMessageStatusCallback(messageSendCallback);
    }

    /**
     * 设置消息接收callback
     */
    protected void setMessageReceiveCallback(){
        if(messageReceiveCallback == null){
            messageReceiveCallback = new EMCallBack() {

                @Override
                public void onSuccess() {
                    updateView(0);
                }

                @Override
                public void onProgress(final int progress, String status) {
                    activity.runOnUiThread(new Runnable() {
                        public void run() {
                            if(percentageView != null){
                                percentageView.setText(progress + "%");
                            }
                        }
                    });
                }

                @Override
                public void onError(int code, String error) {
                    updateView(code);
                }
            };
        }
        message.setMessageStatusCallback(messageReceiveCallback);
    }


    private void setClickListener() {
        if(bubbleLayout != null){
            bubbleLayout.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (itemClickListener != null){
                        if(!itemClickListener.onBubbleClick(message)){
                            //如果listener返回false不处理这个事件，执行lib默认的处理
                            onBubbleClick();
                        }
                    }
                }
            });

            bubbleLayout.setOnLongClickListener(new OnLongClickListener() {

                @Override
                public boolean onLongClick(View v) {
                    if (itemClickListener != null) {
                        itemClickListener.onBubbleLongClick(message);
                    }
                    return true;
                }
            });
        }

        if (statusView != null) {
            statusView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (itemClickListener != null) {
                        itemClickListener.onResendClick(message);
                    }
                }
            });
        }

        userAvatarView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (itemClickListener != null) {

                    if (message.direct() == Direct.SEND) {
                        itemClickListener.onUserAvatarClick(chatBean);
                    } else {
                        itemClickListener.onUserAvatarClick(chatBean);
                    }
                }
            }
        });
    }


    protected void updateView(final int code) {
        activity.runOnUiThread(new Runnable() {
            public void run() {
                if (message.status() == EMMessage.Status.FAIL) {
                    switch (code) {
                        // 网络异常 2
                        case EMError.NETWORK_ERROR:
                            Toast.makeText(activity, "网络错误 " , Toast.LENGTH_LONG).show();
                            break;
                        // 无效的用户名 101
                        case EMError.INVALID_USER_NAME:
                            Toast.makeText(activity, "无效的用户名 "  , Toast.LENGTH_LONG).show();
                            break;
                        // 无效的密码 102
                        case EMError.INVALID_PASSWORD:
                            Toast.makeText(activity, "无效的密码 "  , Toast.LENGTH_LONG).show();
                            break;
                        // 用户认证失败，用户名或密码错误 202
                        case EMError.USER_AUTHENTICATION_FAILED:
                            Toast.makeText(activity, "用户认证失败，用户名或密码错误 "  , Toast.LENGTH_LONG).show();
                            break;
                        // 用户不存在 204
                        case EMError.USER_NOT_FOUND:
                            Toast.makeText(activity, "用户不存在或重新登录"  , Toast.LENGTH_LONG).show();
                            break;
                        // 无法访问到服务器 300
                        case EMError.SERVER_NOT_REACHABLE:
                            Toast.makeText(activity, "无法访问到服务器 "  , Toast.LENGTH_LONG).show();
                            break;
                        // 等待服务器响应超时 301
                        case EMError.SERVER_TIMEOUT:
                            Toast.makeText(activity, "等待服务器响应超时 "  , Toast.LENGTH_LONG).show();
                            break;
                        // 服务器繁忙 302
                        case EMError.SERVER_BUSY:
                            Toast.makeText(activity, "服务器繁忙 "  , Toast.LENGTH_LONG).show();
                            break;
                        // 未知 Server 异常 303 一般断网会出现这个错误
                        case EMError.SERVER_UNKNOWN_ERROR:
                            Toast.makeText(activity, "未知的服务器异常 "  , Toast.LENGTH_LONG).show();
                            break;
                        case EMError.MESSAGE_INCLUDE_ILLEGAL_CONTENT:
                            Toast.makeText(activity,activity.getString(R.string.send_fail) + activity.getString(R.string.error_send_invalid_content), Toast.LENGTH_SHORT).show();
                            break;
                        case EMError.GROUP_NOT_JOINED:
                            Toast.makeText(activity,activity.getString(R.string.send_fail) + activity.getString(R.string.error_send_not_in_the_group), Toast.LENGTH_SHORT).show();
                            break;
                        case EMError.GROUP_PERMISSION_DENIED:
                            Toast.makeText(activity,"您已不在此群", Toast.LENGTH_SHORT).show();
                            break;

                        default:
                            Toast.makeText(activity, "ml_sign_in_failed "  , Toast.LENGTH_LONG).show();
                            break;
                    }
                }

                onUpdateView();
            }
        });

    }

    /**
     * 填充layout
     */
    protected abstract void onInflatView();

    /**
     * 查找chatrow里的控件
     */
    protected abstract void onFindViewById();

    /**
     * 消息状态改变，刷新listview
     */
    protected abstract void onUpdateView();

    /**
     * 设置更新控件属性
     */
    protected abstract void onSetUpView();

    /**
     * 聊天气泡被点击事件
     */
    protected abstract void onBubbleClick();

}
